<template>
    <div class="chart-box flex-column">
        <div class="title-box pd20 flex-row-center">
            <!-- <span class="pointer return flex-row-center mr10" @click="()=>{proxy.routerBackMixin()}"><el-icon><back /></el-icon></span> -->
            <span class="size18">{{proxy.$route.query.persionname}}</span>
        </div>
        <div class="charts pd15" ref="charts_">
			<div class="flex-center mini-size base-color pointer mb10" @click="()=>{updalist();obj.scrollto=false;}">{{obj.toptext}}</div>
			<div v-for="(v,i) in list" :key="i" class="item">
				<!-- 时间 -->
				<div class="flex-center mini-gray-size" v-show="v.showTime"><span>{{v.intime||''}}</span></div>
				
				<div :class="[v.isSender?'column-end':'row-start']">
					<!-- 自己 -->
					<div class="company-name flex-center" v-if="v.isSender">
						<span>我</span>
					</div>
					<!-- 对方 -->
					<div class="head" v-else-if="!v.isSender">
						<el-image style="width: 100px; height: 100px" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" fit="cover" />
					</div>
					
					<!-- 内容 -->
					<div :class="['con',v.isSender?'con-right':'con-left']">
						<div :class="['point',v.isSender?'point-top':'point-left']"></div>
						<!-- 文本 -->
						<span>{{v.msg}}</span>
					</div>
				</div>
			</div> 
        </div>
		<div class="input-box write-bg">
			<el-input v-model="msg" maxlength="300" @keyup.enter="send(msg)" placeholder="请输入内容..." show-word-limit type="textarea" rows="4"/>
			<div class="flex-row ju-flex-end pd10">
				<el-button class="btn-send flex-center base-size" type="primary" :disabled="!msg" @click="send(msg)">发送</el-button>
			</div>
		</div>
    </div>
</template>
<script setup>
    import { reactive,ref,getCurrentInstance,toRefs,toRaw,watch,onMounted,nextTick } from 'vue'

    let { proxy } = getCurrentInstance()
    let obj = reactive({
		sifterForm: {
			"persion_id": proxy.$route.query.persion_id,
			"job_id": proxy.$route.query.job_id,
			"persionname": proxy.$route.query.persionname,
			"currentpage":1,
			"pagesize":10
		},
		scrollto: true,
		toptext: '点击查看更多历史记录',
		total: 0,
        list: [],

		msg: "",
		stompClient: null,
		charts_: null,
		charts_scrollH: 500,
		me: {name:'',head:''},
		other: {name:'',head:''},
    	monitordata: proxy.$Websocket.monitordata
    });

	watch(
		()=>obj.monitordata,
		(msg)=>{
			console.log(msg);
			if(msg.type===`talk`&&msg.job_id===obj.sifterForm.job_id&&msg.persion_id===obj.sifterForm.persion_id){
				if(msg.title){
					let o = {
						isSender: false,
						msg: msg.title
					}
					list.value.push(o)
				}
			}
		},{ deep: true }
	)

	watch(
		()=> [...obj.list],
		(val)=>{
			if(obj.scrollto){
				setTimeout(()=>{
					obj.charts_scrollH = obj.charts_.scrollHeight - 500
					nextTick(()=>{obj.charts_.scrollTo(0,obj.charts_scrollH)})
				},0)
			}
			
			obj.scrollto = true
		},true
	)

	watch(
		()=> proxy.$route.query,
		(val)=>{
			obj.sifterForm = {
				...obj.sifterForm,
				...val,
				currentpage: 1
			}
			updalist(true)
		},true
	)

	onMounted(() => {
		// 监听滚动条位置
		obj.charts_.addEventListener('scroll', scrollTop, true)
	})
	
	// 实时滚动条高度
	const scrollTop = () => {
		let scroll = obj.charts_.scrollTop;
	}
		
    const updalist = (reset)=>{
        proxy.$ajax({url: 'talk/detail',data: obj.sifterForm,bfLoading: true}).then(d => {
            if(d.success){
				list.value = reset?[]:list.value
				if(d.msg.list.length==0){
					obj.toptext = '暂无历史记录'
					return
				}else{
					obj.toptext = '点击查看更多历史记录'
				}
				// 此处需要反转
				let listArr = d.msg.list.reverse();
				for (let i = 0; i < listArr.length; i++) {
					listArr[i].isSender = listArr[i].sender === 'c'
					listArr[i].index = i
				}
				// 此处注意本地数据连接到服务器传的数据 是反过来的
				let localListArr = JSON.parse(JSON.stringify(list.value))
				let listArr1 = listArr.concat(localListArr)
				for (let i = 0; i < listArr1.length; i++) {
					listArr1[i].showTime = (i===0||proxy.$utils.compareTimeInterval(listArr1[i].intime,listArr1[i-1].intime||''))
				}
                list.value = listArr1;
                total.value = d.msg.count||0
				obj.sifterForm.currentpage += 1
				// console.log(list);
            }else{
				obj.sifterForm.currentpage -= 1;
			}
        }).catch(e => {
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
    }
    updalist();

	
	const connectSocket = ()=>{
		proxy.$Websocket.init().then((e)=>{
			let title = `/topic/company/${sessionStorage.getItem("ID")}`;
			proxy.$Websocket.addSubscribe(title);
		})
	}
	connectSocket()

	const send = (value)=>{
		let v = (` ${value}`).replace(/(^\s*)|(\s*$|[\r\n])|<[^>]+>/g, "")
		let param = {
			"persion_id": proxy.$route.query.persion_id,
			"job_id": proxy.$route.query.job_id,
			"msg": v
		}
        proxy.$ajax({url: 'talk',data: param,bfLoading: true}).then(d => {
            if(d.success){
				obj.msg = ''
				let o = {
					isSender: true,
					msg: v,
				}
				list.value.push(o)
            }else{}
        }).catch(e => {
            if(e == "登录已过期，请重新登录"){
                proxy.routerPushMixin('/')
            }
        })
	}

    let { scrollto, list, total, msg,charts_ } = toRefs(obj)
    
</script>

<style lang="scss" scoped>
    .chart-box{overflow: hidden; flex: 1; height:100%;}
    .title-box{background: #fff;box-shadow: 0 2px 10px 0 hsla(0,0%,59.2%,.15);position: relative;z-index: 1;}
    .charts{ flex:1;overflow-y: auto;background: #fefefe;}

	.item{
		display: flex;
		flex-direction: column;
		padding: 10px 0;
		box-sizing: border-box;
		user-select: text;
	}
	.item >view:nth-child(1){
		text-align: center;
		width: 100%;
		padding: 0 0 20px;
		font-size: 14px;
		color: #999;
	}
	.item >view:nth-child(2){
		display: flex;
		user-select: text;
	}
	.column-end{
		display: flex !important;flex-direction: column; align-items: flex-end;
	}
	.column{display: flex;flex-direction: column;}
	.row-start{display: flex;flex-direction: row;}
	.send-state-show{
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background: rgba(0,0,0,0.3);
		font-size: 14px;
		color: #fff;
		letter-spacing: 1px;
	}
	.company-name{
		width: 40px;height: 40px;border-radius: 40px;background: #409eff;
		font-size: 12px;color: #fff;display: block;
	}
	.head{
		width: 40px; height: 40px; border-radius: 40px;background: #fff;overflow: hidden;
	}
	.head image{
		width: 40px; height: 40px; border-radius: 40px;
	}
	.con{
		position: relative;
		display: inline-block;
		border-radius: 5px;
		padding: 10px;
		box-sizing: border-box;
		background: #fff;
		max-width: 90%;
		font-size: 14px;box-shadow: 0 2px 10px 0 hsla(0,0%,59.2%,.15);
	}
	.con-left{
		margin: 0 10px;
		text-align: left;
		background: #409eff;
		color: #fff;
	}
	.con-right{
		margin: 10px 0 0;
		text-align: right;
	}
	.point{
		position: absolute;
		top: 10px;
		z-index: 100;
		width: 0;
		height: 0;
		font-size: 0;
		border-width: 7px;
		border-style: solid;
		overflow: hidden;
	}
	.point-top{
		top: -13px;right:12px;
		border-color: transparent transparent #fff transparent;
	}
	.point-left{
		left: -13px;
		border-color: transparent #409eff transparent transparent;
	}
	.btn-send{
		width: 100px;height: 36px;
	}
	 .input-box ::v-deep .el-textarea__inner {
		border: none;
		box-shadow: none;
		resize: none;/* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
	}
</style>